package lensfield;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFParseException;
import org.openrdf.sail.nativerdf.NativeStore;

/**
 * Thin wrapper around a sesame repository.
 * 
 * @author jimdowning
 * 
 */
public class Triplestore {

	private static final Logger LOG = Logger.getLogger(Triplestore.class);
	private File repoLocation;
	private Repository repository;

	public Triplestore(String repoLocation) {
		this.repoLocation = new File(repoLocation);
	}
	
	public Triplestore(File repoLocation) {
		this.repoLocation = repoLocation;
	}

	public void init() {
		if (!repoLocation.exists()) {
			repoLocation.mkdirs();
		}
		String indices = "spoc,posc,cosp";
		repository = new SailRepository(new NativeStore(repoLocation, indices));
		try {
			repository.initialize();
		} catch (RepositoryException e) {
			throw new RuntimeException("Problem initializing Sesame: "
					+ e.getMessage(), e);
		}
		LOG.info("Initialized triplestore on application");
	}

	public void stop() {
		try {
			repository.shutDown();
		} catch (RepositoryException e) {
			throw new RuntimeException(e);
		}
	}

	public RepositoryConnection openConnection() {
		try {
			return repository.getConnection();
		} catch (RepositoryException e) {
			throw new RuntimeException(e);
		}
	}

	public void addFile(RepositoryConnection conn, File dataFile, String baseRef) {
		RDFFormat rdfFormat = RDFFormat.forFileName(dataFile.getAbsolutePath());
		try {
			conn.add(dataFile, baseRef, rdfFormat);
		} catch (RDFParseException e) {
			throw new RuntimeException("Request entity was not valid "
					+ rdfFormat + ": " + e.getMessage(), e);
		} catch (RepositoryException e) {
			throw new RuntimeException("Could not add RDF to triplestore: "
					+ e.getMessage(), e);
		} catch (IOException e) {
			throw new RuntimeException("Could not add RDF to triplestore: "
					+ e.getMessage(), e);
		}
	}

	public void closeQuietly(RepositoryConnection con) {
		if (con == null) {
			return;
		} else {
			try {
				con.close();
			} catch (RepositoryException e) {
				LOG.info("Problem closing connection: " + e.getMessage(), e);
			}
		}
	}
	
	public static void main(String[] args) {
		String location = "c:/Users/ned24/workspace/lensfield/data/Gau_output";
		Triplestore store = new Triplestore(location);
		store.init();
		RepositoryConnection conn = store.openConnection();
		File dataFile = new File(location+"/(CH3)3SiO/(CH3)3SiO.gau.cml.rdf");
		store.addFile(conn, dataFile, "_baseref_");
	}

}
